package com.zyh.thread.demo6;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zyh
 * @Date 2024/8/8 14:44
 * @Description 创建一个桌子类
 */

public class Stack {
    private Product product;//商品
    private Boolean flag;//标记

    public Stack() {
    }

    public Stack(Product product, Boolean flag) {
        this.product = product;
        this.flag = flag;
    }


    //创建lock锁
    Lock lock = new ReentrantLock();
    Condition create_lock = lock.newCondition();//创建生产者锁
    Condition eat_lock = lock.newCondition();//创建消费者锁


    /*
        生产商品的方法
     */
    public void create(String name, String color) {
        try {
            lock.lock();
            while (flag) {//说明桌子有商品，则生产线程进行阻塞
                try {
                    create_lock.await();//this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //生产商品
            product.setName(name);
            product.setColor(color);
            System.out.println(Thread.currentThread().getName() + "生产了：" + product.getColor() + "的" + product.getName());
            //生产后桌子有商品，将flag改为true
            flag = true;
            //唤醒消费线程
            eat_lock.signal();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /*
        消费商品的方法
     */
    public void eat() {
        try {
            //判断桌子是否有商品
            lock.lock();
            while (flag == false) {//没有商品就等待
                try {
                    eat_lock.await();//this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Thread.sleep(10);
            //有商品就消费
            System.out.println(Thread.currentThread().getName() + "消费了：" + product.getColor() + "的" + product.getName());
            //消费后
            flag = false;
            //唤醒生产者线程
            create_lock.signal();//this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
